package com.bea.ftd.encrypt.controller;

import java.io.*;
import java.util.Properties;

import com.bea.ftd.common.enums.EncryptEnum;
import com.bea.ftd.common.enums.ErrorCode;
import com.bea.ftd.common.model.EncryptRequest;
import com.bea.ftd.common.model.EncryptResponse;
import com.bea.ftd.common.utils.SystemUtil;
import com.bea.ftd.encrypt.entity.GatewayRequest;
import com.bea.ftd.encrypt.entity.SmRequest;
import com.bea.ftd.encrypt.service.GatewayEnOpStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.hibernate.validator.internal.util.Contracts.assertNotNull;

@RestController
@PropertySource(value = { "classpath:keys.properties" })
public class SignatrueController {
	private static final Logger logger = LoggerFactory.getLogger(SignatrueController.class.getName());

	@Autowired
	private GatewayEnOpStep gatewayEnOpStep;

	@RequestMapping("/gatewayForward")
	public EncryptResponse gatewayForward(@RequestBody EncryptRequest request){
		EncryptResponse response = new EncryptResponse();
		try{
			if(request.getEncryptStrategy()==2&&EncryptEnum.RSA.equals(request.getSignType())){
				logger.info("调用签名接口开始......电商渠道[{}]签名内容[{}]",request.getPartnerCode(),request.getData());
				String result = gatewayEnOpStep.generateSignature(request.getPartnerCode(), request.getData());
				logger.info("接口返回签名结果......[{}]",result);
				if("0".equals(result)){
					SystemUtil.handleResponse(response, ErrorCode.SIGN_ERROR);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(result);
				}
			}
			if(request.getEncryptStrategy()==4&&EncryptEnum.RSA.equals(request.getSignType())){
				logger.info("调用验签接口开始......电商渠道[{}]验签内容[{}]密文[{}]",request.getPartnerCode(),request.getData(),request.getSign());
				boolean result = gatewayEnOpStep.verifySiginature(request.getPartnerCode(), request.getSign(), request.getData());
				logger.info("接口返回验签结果......[{}]",result);
				if (false==result){
					SystemUtil.handleResponse(response, ErrorCode.VERIFY_ERROR);
					response.setData(false);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(true);
				}
			}
			if (request.getEncryptStrategy()==1&&EncryptEnum.SM2.equals(request.getSignType())){
				logger.info("调用sm2加密接口开始......电商渠道[{}]加密内容[{}]",request.getPartnerCode(),request.getData());
				String encrypt = gatewayEnOpStep.Sm2Encrypt(request.getPartnerCode(),request.getData());
				logger.info("接口返回sm2加密结果......[{}]",encrypt);
				if ("0".equals(encrypt)){
					SystemUtil.handleResponse(response, ErrorCode.ENCRYPT_SM2_ERROR);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(encrypt);
				}
			}
			if (request.getEncryptStrategy()==3&&EncryptEnum.SM2.equals(request.getSignType())){
				logger.info("调用sm2解密接口开始......电商渠道[{}]解密内容[{}]",request.getPartnerCode(),request.getData());
				String decrypt = gatewayEnOpStep.Sm2Decrypt(request.getPartnerCode(),request.getData());
				logger.info("接口返回sm2解密结果......[{}]",decrypt);
				if ("0".equals(decrypt)){
					SystemUtil.handleResponse(response, ErrorCode.DECRYPT_SM2_ERROR);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(decrypt);
				}
			}
			if (request.getEncryptStrategy()==1&&EncryptEnum.SM4ECB.equals(request.getSignType())){
				logger.info("调用ECB加密接口开始......电商渠道[{}]加密内容[{}]",request.getPartnerCode(),request.getData());
				String encrypt = gatewayEnOpStep.EncryptECB(request.getPartnerCode(),request.getData());
				logger.info("接口返回ECB加密结果......[{}]",encrypt);
				if ("0".equals(encrypt)){
					SystemUtil.handleResponse(response, ErrorCode.ENCRYPT_ECB_ERROR);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(encrypt);
				}
			}
			if (request.getEncryptStrategy()==3&&EncryptEnum.SM4ECB.equals(request.getSignType())){
				logger.info("调用ECB解密接口开始......电商渠道[{}]解密内容[{}]",request.getPartnerCode(),request.getData());
				String decrypt = gatewayEnOpStep.DecryptECB(request.getPartnerCode(),request.getData());
				logger.info("接口返回ECB加密结果......[{}]",decrypt);
				if ("0".equals(decrypt)){
					SystemUtil.handleResponse(response, ErrorCode.DECRYPT_ECB_ERROR);
				}else{
					SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
					response.setData(decrypt);
				}
			}
			return response;
		}catch (Exception e){
			SystemUtil.handleResponse(response, ErrorCode.SUCCESS);
			return response;
		}

	}

	/**
	 * 验签
	 * @param request
	 * @return
	 */
	@RequestMapping("/verifySign")
	public boolean rsaVerifySign(@RequestBody GatewayRequest request) {
		logger.info("开始验签......");
		if (StringUtils.isEmpty(request.getContext())) {
			logger.error("验签内容不能为空");
		}
		boolean res =  gatewayEnOpStep.verifySiginature(request.getPartnerCode(), request.getSignature(), request.getContext());
		return res;

	}

	/**
	 * 签名
	 * @param request
	 * @return
	 */
	@RequestMapping("/sign")
	public String rsaSign(@RequestBody GatewayRequest request) {
		if (StringUtils.isEmpty(request.getContext())) {
			logger.error("签名内容不能为空");
		}
		return gatewayEnOpStep.generateSignature(request.getPartnerCode(), request.getContext());
	}

	@RequestMapping("/sm2Encrypt")
	public String sm2Encrypt(@RequestBody SmRequest request){
		if (StringUtils.isEmpty(request.getData())) {
			logger.error("加密内容不能为空");
		}
		String encrypt = gatewayEnOpStep.Sm2Encrypt(request.getPartnerCode(),request.getData());
		return encrypt;
	}

	@RequestMapping("/sm2Decrypt")
	public String sm2Decrypt(@RequestBody SmRequest request){
		if (StringUtils.isEmpty(request.getData())) {
			logger.error("加密内容不能为空");
		}
		String encrypt = gatewayEnOpStep.Sm2Decrypt(request.getPartnerCode(),request.getData());
		return encrypt;
	}

	@RequestMapping("/encryptECB")
	public String encryptECB(@RequestBody SmRequest request){
		if (StringUtils.isEmpty(request.getData())) {
			logger.error("加密内容不能为空");
		}
		String encrypt = gatewayEnOpStep.EncryptECB(request.getPartnerCode(),request.getData());
		return encrypt;
	}

	@RequestMapping("/decryptECB")
	public String decryptECB(@RequestBody SmRequest request){
		if (StringUtils.isEmpty(request.getData())) {
			logger.error("解密内容不能为空");
		}
		String encrypt = gatewayEnOpStep.DecryptECB(request.getPartnerCode(),request.getData());
		return encrypt;
	}

	@RequestMapping("/hello")
	public String hello(){
		Properties properties = new Properties();
//		Properties properties = System.getProperties();
//		Enumeration pnames = properties.propertyNames();
//		String pname = null;
//		while (pnames.hasMoreElements()) {
//			pname= (String) pnames.nextElement();
//			System.out.print(pname + "--------------");
//			System.out.println(properties.getProperty(pname));
//		}
//		String relativelyPath = properties.getProperty("user.dir");
//		File file01 = new File("encrypt/src/main/resources/keys.properties");
//		System.out.println(file01.getAbsolutePath());
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new FileReader("encrypt/src/main/resources/keys.properties"));
			properties.load(bufferedReader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 获取key对应的value值
		String result = properties.getProperty("ant.privateKey");

//		File file02 = new File(properties.getProperty("user.dir") + "/bin/config/keys.properties");
//		System.out.println(file02.getAbsolutePath());


		System.out.println(EncryptEnum.SM4ECB.getName());
		return result;
	}
}